﻿using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using Taobao.Top.Api;
using Taobao.Top.Api.Domain;
using Taobao.Top.Api.Request;

namespace Taobao.open.api
{
    /// <summary>
    /// Copyright @2009 Taobao.com
    /// </summary>
    partial class MainForm : System.Windows.Forms.Form
    {
        [STAThreadAttribute]
        static void Main()
        {
            Application.Run(new MainForm());
        }

        public MainForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Designer variable used to keep track of non-visual components.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Disposes resources used by the form.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (components != null)
                {
                    components.Dispose();
                }
            }
            base.Dispose(disposing);
        }

        /// <summary>
        /// This method is required for Windows Forms designer support.
        /// Do not change the method contents inside the source code editor. The Forms designer might
        /// not be able to load this method if it was changed manually.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.picInfo = new System.Windows.Forms.PictureBox();
            this.label1 = new System.Windows.Forms.Label();
            this.btnGetKey = new System.Windows.Forms.Button();
            this.btnPasteKey = new System.Windows.Forms.Button();
            this.txtAuthCode = new System.Windows.Forms.TextBox();
            this.btnStart = new System.Windows.Forms.Button();
            this.tradeDataGrid = new System.Windows.Forms.DataGridView();
            ((System.ComponentModel.ISupportInitialize)(this.picInfo)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.tradeDataGrid)).BeginInit();
            this.SuspendLayout();
            // 
            // picInfo
            // 
            this.picInfo.ErrorImage = ((System.Drawing.Image)(resources.GetObject("picInfo.ErrorImage")));
            this.picInfo.Image = ((System.Drawing.Image)(resources.GetObject("picInfo.Image")));
            this.picInfo.Location = new System.Drawing.Point(12, 28);
            this.picInfo.Name = "picInfo";
            this.picInfo.Size = new System.Drawing.Size(124, 124);
            this.picInfo.TabIndex = 0;
            this.picInfo.TabStop = false;
            // 
            // label1
            // 
            this.label1.Location = new System.Drawing.Point(142, 28);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(288, 126);
            this.label1.TabIndex = 1;
            this.label1.Text = "您好，尊敬的用户。\r\n“淘宝卖家订单查询DEMO”将访问您的店铺中的订单。需要您的淘宝TOP授权码。";
            // 
            // btnGetKey
            // 
            this.btnGetKey.BackColor = System.Drawing.Color.NavajoWhite;
            this.btnGetKey.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.btnGetKey.Location = new System.Drawing.Point(142, 83);
            this.btnGetKey.Name = "btnGetKey";
            this.btnGetKey.Size = new System.Drawing.Size(156, 30);
            this.btnGetKey.TabIndex = 2;
            this.btnGetKey.Text = "获取淘宝授权码";
            this.btnGetKey.UseVisualStyleBackColor = false;
            this.btnGetKey.Click += new System.EventHandler(this.BtnGetKeyClick);
            // 
            // btnPasteKey
            // 
            this.btnPasteKey.BackColor = System.Drawing.Color.NavajoWhite;
            this.btnPasteKey.Location = new System.Drawing.Point(12, 158);
            this.btnPasteKey.Name = "btnPasteKey";
            this.btnPasteKey.Size = new System.Drawing.Size(286, 23);
            this.btnPasteKey.TabIndex = 3;
            this.btnPasteKey.Text = "从剪切板上粘贴授权码";
            this.btnPasteKey.UseVisualStyleBackColor = false;
            this.btnPasteKey.Click += new System.EventHandler(this.BtnPasteKeyClick);
            // 
            // txtAuthCode
            // 
            this.txtAuthCode.Location = new System.Drawing.Point(12, 187);
            this.txtAuthCode.Multiline = true;
            this.txtAuthCode.Name = "txtAuthCode";
            this.txtAuthCode.RightToLeft = System.Windows.Forms.RightToLeft.No;
            this.txtAuthCode.Size = new System.Drawing.Size(286, 51);
            this.txtAuthCode.TabIndex = 0;
            this.txtAuthCode.Text = "\r\n请填入淘宝TOP授权码";
            this.txtAuthCode.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            // 
            // btnStart
            // 
            this.btnStart.BackColor = System.Drawing.Color.PaleGoldenrod;
            this.btnStart.Location = new System.Drawing.Point(305, 158);
            this.btnStart.Name = "btnStart";
            this.btnStart.Size = new System.Drawing.Size(86, 80);
            this.btnStart.TabIndex = 5;
            this.btnStart.Text = "开始";
            this.btnStart.UseVisualStyleBackColor = false;
            this.btnStart.Click += new System.EventHandler(this.BtnStartClick);
            // 
            // dataGridView1
            // 
            this.tradeDataGrid.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            this.tradeDataGrid.Location = new System.Drawing.Point(0, 0);
            this.tradeDataGrid.Name = "dataGridView1";
            this.tradeDataGrid.RowTemplate.Height = 23;
            this.tradeDataGrid.Size = new System.Drawing.Size(745, 400);
            this.tradeDataGrid.TabIndex = 6;
            // 
            // MainForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.BackColor = System.Drawing.Color.FloralWhite;
            this.ClientSize = new System.Drawing.Size(479, 400);
            this.Controls.Add(this.btnStart);
            this.Controls.Add(this.txtAuthCode);
            this.Controls.Add(this.btnPasteKey);
            this.Controls.Add(this.btnGetKey);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.picInfo);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "MainForm";
            this.Text = "淘宝卖家订单查询DEMO";
            ((System.ComponentModel.ISupportInitialize)(this.picInfo)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.tradeDataGrid)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        private System.Windows.Forms.DataGridView tradeDataGrid;
        private System.Windows.Forms.Button btnStart;
        private System.Windows.Forms.TextBox txtAuthCode;
        private System.Windows.Forms.Button btnPasteKey;
        private System.Windows.Forms.Button btnGetKey;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.PictureBox picInfo;

        void BtnGetKeyClick(object sender, System.EventArgs e)
        {
            //get the authurize code from taobao open platform
            OpenIE("http://open.taobao.com/isv/authorize.php?appkey=test");
        }

        void BtnPasteKeyClick(object sender, System.EventArgs e)
        {
            // 获取剪切板的内容，并按行分割
            string pasteText = Clipboard.GetText();
            this.txtAuthCode.Text = pasteText;
        }

        void BtnStartClick(object sender, System.EventArgs e)
        {
            string sessionKey = getSessionKey(this.txtAuthCode.Text);
            if (sessionKey.StartsWith("Error"))
            {
                MessageBox.Show("获取SessionKey失败，请更换您的授权码");
                return;
            }

            DataTable table = CreateTable();
            TopXmlRestClient topClient = new TopXmlRestClient("http://gw.api.tbsandbox.com/router/rest", "test", "test");
            TradesSoldGetRequest req = new TradesSoldGetRequest();
            req.Fields = "tid,seller_nick,buyer_nick,status,orders.title,orders.price,orders.num";
            req.PageSize = 18;
            ResponseList<Trade> rsp = topClient.GetSoldTrades(req, sessionKey);
            if (rsp.Content == null || rsp.Content.Count < 1)
            {
                MessageBox.Show("此会员没有订单，请更换其他会员帐号获取授权码重试");
                return;
            }

            List<Trade> trades = rsp.Content;
            foreach (Trade trade in trades)
            {
                DataRow r1 = table.NewRow();
                r1["卖家昵称"] = trade.SellerNick;
                r1["买家昵称"] = trade.BuyerNick;
                r1["订单编号"] = trade.Tid;
                r1["订单状态"] = trade.Status;
                if (trade.OrderList != null && trade.OrderList.Count > 0)
                {
                    Order order = trade.OrderList[0];
                    r1["商品标题"] = order.ItemTitle;
                    r1["价格"] = order.ItemPrice;
                    r1["数量"] = order.ItemNum;
                }
                table.Rows.Add(r1);
            }


            tradeDataGrid.DataSource = table;
            Controls.Clear();
            Controls.Add(tradeDataGrid);

            AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new System.Drawing.Size(745, 400);

            ResumeLayout(false);
            PerformLayout();

            tradeDataGrid.Columns[4].Width = 120;
            tradeDataGrid.Columns[6].Width = 80;

            for (int i = 0; i < tradeDataGrid.Rows.Count; )
            {
                tradeDataGrid.Rows[i].DefaultCellStyle.BackColor = System.Drawing.Color.LemonChiffon;
                i += 2;
            }

            tradeDataGrid.BackgroundColor = System.Drawing.Color.Wheat;
        }

        private DataTable CreateTable()
        {
            DataTable table = new DataTable();
            DataColumn c1 = new DataColumn("订单编号", typeof(string));
            table.Columns.Add(c1);
            DataColumn c2 = new DataColumn("买家昵称", typeof(string));
            table.Columns.Add(c2);
            DataColumn c3 = new DataColumn("卖家昵称", typeof(string));
            table.Columns.Add(c3);
            DataColumn c4 = new DataColumn("订单状态", typeof(string));
            table.Columns.Add(c4);
            DataColumn c5 = new DataColumn("商品标题", typeof(string));
            table.Columns.Add(c5);
            DataColumn c6 = new DataColumn("价格", typeof(string));
            table.Columns.Add(c6);
            DataColumn c7 = new DataColumn("数量", typeof(string));
            table.Columns.Add(c7);
            return table;
        }

        void OpenIE(string sUrl)
        {
            object url = sUrl;

            try
            {
                // Asks default browser to visit the specified site.
                ShellExecute(IntPtr.Zero, "open", sUrl, "", "", ShowCommands.SW_SHOWNOACTIVATE);

            }
            catch (Exception e)
            {
                Console.WriteLine("Exception when creating Internet  Explorer object {0}", e);
                return;
            }
        }

        public string getSessionKey(string auth_code)
        {
            try
            {
                // Create a request for the URL.         
                WebRequest request = WebRequest.Create("http://container.api.tbsandbox.com/container?authcode=" + auth_code);

                // Get the response.
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                if (response.StatusCode != HttpStatusCode.OK) return "Error";

                // Get the stream containing content returned by the server.
                Stream dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                StreamReader reader = new StreamReader(dataStream);
                // Read the content.
                string responseFromServer = reader.ReadToEnd();
                string[] sArray = responseFromServer.Split('&');

                foreach (string i in sArray)
                {
                    if (i.ToString().StartsWith("top_session")) return i.ToString().Substring(i.ToString().IndexOf("=") + 1);
                }

                // Display the content.
                // Console.WriteLine (responseFromServer);
                // Cleanup the streams and the response.
                reader.Close();
                dataStream.Close();
                response.Close();

                return responseFromServer;
            }
            catch (WebException e)
            {
                return "Error:" + e.Status;
            }
            catch (Exception e)
            {
                return "Error:" + e.Message;
            }
        }


        public enum ShowCommands : int
        {
            SW_HIDE = 0,
            SW_SHOWNORMAL = 1,
            SW_NORMAL = 1,
            SW_SHOWMINIMIZED = 2,
            SW_SHOWMAXIMIZED = 3,
            SW_MAXIMIZE = 3,
            SW_SHOWNOACTIVATE = 4,
            SW_SHOW = 5,
            SW_MINIMIZE = 6,
            SW_SHOWMINNOACTIVE = 7,
            SW_SHOWNA = 8,
            SW_RESTORE = 9,
            SW_SHOWDEFAULT = 10,
            SW_FORCEMINIMIZE = 11,
            SW_MAX = 11
        }

        [DllImport("shell32.dll")]
        static extern IntPtr ShellExecute(
            IntPtr hwnd,
            string lpOperation,
            string lpFile,
            string lpParameters,
            string lpDirectory,
            ShowCommands nShowCmd);

    }
}
